<template>
  <div class="deviceDetail">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="back" @click="goBack">←返回</div>
      <h1>设备-{{ form.deviceName }}-详情</h1>
      <div class="title">
        设备基本信息
        <span class="status">{{
          form.stopFlag == '1'
            ? '已停用'
            : form.deviceStatus == '1'
            ? '使用中'
            : form.deviceStatus == '2'
            ? '维修中'
            : form.deviceStatus == '3'
            ? '维保中'
            : form.deviceStatus == '4'
            ? '点检中'
            : ''
        }}</span>
      </div>
      <div class="row">
        <div>设备编号: {{ form.deviceNum }}</div>
        <div>设备名称: {{ form.deviceName }}</div>
        <div>设备类型: {{ form.deviceTypeName }}</div>
      </div>
      <div class="row">
        <div>设备型号: {{ form.modelName }}</div>
        <div>位置号: {{ form.seatNum }}</div>
        <div>所在部门: {{ form.deptName }}</div>
      </div>
      <div class="row">
        <div>
          设备二维码:
          <!-- <qrcode-vue :value="form.id" :size="100" level="H" /> -->
          <el-image
            style="width: 100px; height: 100px"
            :src="form.qrCodePicture"
            :zoom-rate="1.2"
            :preview-src-list="srcList"
            :initial-index="1"
            fit="cover"
          />
          <!-- <span style="margin-left: 10px;cursor: pointer;color: var(--el-color-primary);"
                        @click="chakan(form.qrCodePicture, 1)">查看</span> -->
          <span
            style="
              margin-left: 10px;
              cursor: pointer;
              color: var(--el-color-primary);
            "
            v-if="buttonDisplayOrNot(buttonCodes, 'deviceExportOneQRCodeBtn')"
            @click="daochu(form.id)"
            >导出</span
          >
        </div>
      </div>
      <el-divider />
      <div class="title">购买安装信息</div>
      <div class="row">
        <div>设备价值(万元): {{ form.deviceCost }}</div>
        <div>能耗(KW/h): {{ form.energyConsumption }}</div>
      </div>
      <div class="row">
        <div>购买日期: {{ form.purchaseDate }}</div>
        <div>投产日期: {{ form.operationDate }}</div>
        <div>供应商: {{ form.purveyorName }}</div>
      </div>
      <div class="row">
        <div>使用年限: {{ form.usefulLife ? form.usefulLife + '年' : '' }}</div>
        <div>品牌: {{ form.brand }}</div>
        <div>厂家: {{ form.manufacturer }}</div>
      </div>
      <div class="row">
        <div>
          设备照片:
          <el-image
            v-if="form.devicePicture != ''"
            style="width: 100px; height: 100px"
            :src="form.devicePicture"
            :zoom-rate="1.2"
            :preview-src-list="srcList"
            :initial-index="0"
            fit="cover"
          />
          <!-- <span v-if="form.devicePicture != ''" style="margin-left: 10px;cursor: pointer;color: var(--el-color-primary);"
                        @click="chakan(form.devicePicture, 2)">查看</span> -->
        </div>
      </div>
      <el-divider />
      <el-row>
        <el-col :span="2">
          <div class="title">备件使用情况</div>
        </el-col>
        <el-col :span="8">
          <div>
            使用备件数量：{{ form.totalAmount }}；使用备件总价值：{{
              form.totalMoney
            }}元
          </div>
        </el-col>
        <el-col :span="8">
          <div>
            备件类型
            <el-cascader
              :show-all-levels="false"
              v-model="partVal"
              :props="cascaderProps"
              :options="partType"
              @change="partChange"
              clearable
            />
          </div>
        </el-col>
      </el-row>
      <Table
        ref="tableRef"
        v-bind="state.tableData"
        class="table-demo"
        @pageChange="onTablePageChange"
        style="width: 60%"
      >
      </Table>
      <EnlargePicture
        :pictureDialog="pictureDialog"
        :pictureForm="pictureForm"
        @closePicture="closePicture"
      >
      </EnlargePicture>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, defineAsyncComponent, onMounted } from 'vue'
import routes from '/@/router'
import { useRoute } from 'vue-router'
import QrcodeVue from 'qrcode.vue'
import { deviceDetailApi, deviceQrCodeReportApi } from '/@/api/assets/index'
import {
  bindFileUrlApi,
  dictionaryList,
  getButtonListByRoleApi
} from '/@/api/publicApi'
import { ElMessage } from 'element-plus'
import { Session } from '/@/utils/storage'
import { buttonDisplayOrNot } from '../../utils/buttonBoolean'
const menu = Session.get('menu')
const buttonCodes = ref<any>([])
const Table = defineAsyncComponent(
  () => import('/@/components/table/index.vue')
)
const EnlargePicture = defineAsyncComponent(
  () => import('./components/EnlargePicture.vue')
)
const route = useRoute()
const id = ref(route.query.id)
const active = ref(route.query.activeName)
const goBack = () => {
  routes.push({
    name: 'assetsEquipment',
    query: {
      active: active.value
    }
  })
}

const srcList = ref<any>([])
const form = ref({
  id: '',
  deviceNum: '',
  deviceName: '',
  deviceTypeName: '',
  modelName: '',
  seatNum: '',
  deptName: '',
  deviceStatus: '',
  deviceCost: '',
  energyConsumption: '',
  purchaseDate: '',
  operationDate: '',
  purveyorName: '',
  totalAmount: '',
  totalMoney: '',
  brand: '',
  devicePicture: '',
  qrCodePicture: '',
  stopFlag: '',
  usefulLife: '',
  manufacturer: ''
})
// 定义变量内容
const tableRef = ref<RefType>()
const state = reactive<TableDemoState>({
  tableData: {
    flash: false, // 刷新表格
    // 表头内容（必传，注意格式）
    header: [
      { key: 'partNum', colWidth: '', title: '备件编号', type: 'text' },
      { key: 'partName', colWidth: '', title: '备件名称', type: 'text' },
      { key: 'partTypeName', colWidth: '', title: '备件类型', type: 'text' },
      { key: 'totalAmount', colWidth: '', title: '备件使用数量', type: 'text' },
      { key: 'totalMoney', colWidth: '', title: '使用备件总价值', type: 'text' }
    ],
    // 配置项（必传）
    config: {
      listApi: '/device/mobile/deviceInfo/partUsageListByDeviceId',
      listHttp: 'post',
      total: 0, // 列表总数
      loading: true, // loading 加载
      noPage: false, // 是否分页
      isSerialNo: true, // 是否显示表格序号
      isSelection: false, // 是否显示表格多选
      isOperate: false, // 是否显示表格操作栏
      isExtend: false // 是否可以扩展
    },
    // 搜索参数
    param: {
      deviceId: '', // 必传参数，分页的不要传
      partType: ''
    }
  }
})

const getDeviceDetail = () => {
  deviceDetailApi(id.value).then((res) => {
    if (res.code == 0) {
      form.value = res.data
      state.tableData.param.deviceId = id.value
      bindFileUrlApi(res.data.qrCodePicture).then((r) => {
        if (r.code == 0) {
          form.value.qrCodePicture = r.data
          srcList.value.push(form.value.qrCodePicture)
        }
      })
      srcList.value.push(form.value.devicePicture)
      getTableData()
    }
  })
}
getDeviceDetail()
const cascaderProps = {
  expandTrigger: 'click' as const,
  value: 'id',
  label: 'configValue',
  emitPath: false
}
const partVal = ref('0')
const partType = ref<any>([])
const getSpareType = () => {
  dictionaryList({ configType: 'part_type', keyword: '' }).then((res) => {
    if (res.code == 0) {
      partType.value = res.data
      partType.value.unshift({
        configValue: '全部',
        customizeFlag: 1,
        parentId: '0',
        id: '0'
      })
    }
  })
}
getSpareType()

// 初始化列表数据
const getTableData = () => {
  state.tableData.flash = !state.tableData.flash
}
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum
  state.tableData.param.pageSize = page.pageSize
  getTableData()
}

const partChange = (val: any) => {
  state.tableData.param.partType = val
  getTableData()
}

const pictureDialog = ref(false)
const pictureForm = ref({
  val: '',
  type: 0,
  name: ''
})
const chakan = (data: any, type: any) => {
  pictureForm.value.val = data
  pictureForm.value.type = type
  pictureForm.value.name = form.value.deviceName
  pictureDialog.value = !pictureDialog.value
}
const closePicture = () => {
  pictureDialog.value = !pictureDialog.value
}

let timer: any = null
const daochu = (id: any) => {
  timer && clearTimeout(timer)
  timer = setTimeout(() => {
    let params = {
      deviceId: id
    }
    deviceQrCodeReportApi(params).then((res: any) => {
      let blob = new Blob([res], {
        type: 'application/png;charset=UTF-8'
      })
      let url = window.URL.createObjectURL(blob)
      const link = document.createElement('a') // 创建a标签
      link.download = form.value.deviceName + '二维码.png'
      link.href = url
      link.click()
      URL.revokeObjectURL(url) // 释放内存
    })
  }, 1000)
}

// 页面加载时
onMounted(() => {
  menu.forEach(async (element: any) => {
    if (element.menuUrl == '/assets/equipment') {
      let res = await getButtonListByRoleApi({
        terminalType: 1,
        menuPid: element.id
      })
      res.data.forEach((item: any) => {
        buttonCodes.value.push(item.buttonCode)
      })
    }
  })
})
</script>
<style scoped lang="scss">
.deviceDetail {
  font-size: var(--el-font-size-base);

  h1 {
    font-size: 18px;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .back {
    cursor: pointer;
    color: rgba(140, 140, 140, 1);
    margin-bottom: 10px;
  }

  .row {
    display: flex;
    margin: 15px 0px;
    padding-left: 10px;

    > div {
      max-width: 400px;
      min-width: 300px;
      margin-right: 50px;
      line-height: 30px;

      .click {
        color: aqua;
        cursor: pointer;
      }

      .photo {
        text-decoration: underline;
      }
    }
  }

  .title {
    font-size: 16px;
    font-weight: 600;

    .status {
      height: 100%;
      border-radius: 32px;
      font-size: 14px;
      background: rgba(25, 98, 224, 0.15);
      padding: 5px;
      color: rgba(25, 98, 224, 1);
      margin-left: 16px;
    }
  }
}
</style>
<style>
.el-button--warning.is-plain {
  --el-button-bg-color: #fdf6ec;
  --el-button-hover-text-color: #e6a23c;
  --el-button-hover-bg-color: #fdf6ec;
}
.el-button--warning.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #e6a23c;
}
.el-button--danger.is-plain {
  --el-button-bg-color: #fef0f0;
  --el-button-hover-text-color: #f56c6c;
  --el-button-hover-bg-color: #fef0f0;
}
.el-button--danger.is-plain:hover {
  --el-button-hover-text-color: #fff;
  --el-button-hover-bg-color: #f56c6c;
}
</style>
